import { useContext, Suspense } from 'react';
import { Switch, Route, Redirect } from 'react-router-dom';
import { observer, MobXProviderContext } from 'mobx-react';

const PrivateRoute = observer((props) => {
  const {
    component: Component, auth, isLogin, ...rest
  } = props;

  return (
    <Route
      {...rest}
      render={({ location }) => (isLogin ? <Component />
        : <Redirect to={{ pathname: '/login', state: { redirect: location.pathname } }} />)}
    />
  );
});

export default observer((props) => {
  const { routers } = props;
  const { appStore } = useContext(MobXProviderContext);
  return (
    <Suspense fallback={<div>Loading...</div>}>
      <Switch>
        {routers.map((router) => {
          const { component: Component, auth, ...rest } = router;
          return auth ? <PrivateRoute key={rest.path} {...router} isLogin={appStore.isLogin} />
            : <Route key={rest.path} {...rest} render={(routes) => (<Component {...routes} />)} />;
        })}
      </Switch>
    </Suspense>
  );
});
